// pages/company/card.js
const companyService = require('../../services/company.js')

Page({
  data: {
    // 页面状态
    loading: false,
    refreshing: false,
    loadingMore: false,
    
    // 卡片列表数据
    cardList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    
    // 公司信息
    companyInfo: null,
    
    // 空状态
    showEmpty: false
  },

  onLoad(options) {
    this.loadCompanyCards(true)
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadCompanyCards(true)
  },

  /**
   * 加载公司卡片列表
   * @param {boolean} refresh 是否刷新（重置页码）
   */
  async loadCompanyCards(refresh = false) {
    if (this.data.loading) return

    try {
      this.setData({
        loading: true,
        refreshing: refresh
      })

      const params = {
        page: refresh ? 1 : this.data.page,
        page_size: this.data.pageSize
      }

      const result = await companyService.getCompanyCards(params)

      if (result.success) {
        const newCards = result.data.list || []
        const total = result.data.total || 0
        const currentPage = result.data.current_page || 1
        const lastPage = result.data.last_page || 1

        wx.setNavigationBarTitle({
          title: result.data.company.name
        })

        this.setData({
          cardList: refresh ? newCards : [...this.data.cardList, ...newCards],
          page: currentPage + 1,
          hasMore: currentPage < lastPage,
          companyInfo: result.data.company,
          showEmpty: refresh && newCards.length === 0,
          loading: false,
          refreshing: false
        })
      } else {
        wx.showToast({
          title: result.message || '获取卡片列表失败',
          icon: 'none'
        })
        this.setData({
          loading: false,
          refreshing: false
        })
      }
    } catch (error) {
      console.error('加载公司卡片失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({
        loading: false,
        refreshing: false
      })
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadCompanyCards(true).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMore()
    }
  },

  /**
   * 加载更多数据
   */
  async loadMore() {
    if (!this.data.hasMore || this.data.loadingMore) return

    try {
      this.setData({ loadingMore: true })

      const params = {
        page: this.data.page,
        page_size: this.data.pageSize
      }

      const result = await companyService.getCompanyCards(params)

      if (result.success) {
        const newCards = result.data.list || []
        const currentPage = result.data.current_page || 1
        const lastPage = result.data.last_page || 1

        this.setData({
          cardList: [...this.data.cardList, ...newCards],
          page: currentPage + 1,
          hasMore: currentPage < lastPage,
          loadingMore: false
        })
      } else {
        wx.showToast({
          title: result.message || '加载更多失败',
          icon: 'none'
        })
        this.setData({ loadingMore: false })
      }
    } catch (error) {
      console.error('加载更多失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({ loadingMore: false })
    }
  },

  /**
   * 查看卡片详情
   */
  onCardDetail(e) {
    const cardId = e.currentTarget.dataset.id
    // 这里可以跳转到卡片详情页面
    wx.showToast({
      title: '卡片详情功能开发中',
      icon: 'none'
    })
  },

  /**
   * 重新加载
   */
  onReload() {
    this.loadCompanyCards(true)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的公司卡片',
      path: '/pages/company/card'
    }
  },

  /**
   * 跳转到卡片激活记录明细页面
   */
  toDetail(e) {
    const cardId = e.currentTarget.dataset.id
    const cardIndex = e.currentTarget.dataset.index
    const cardInfo = this.data.cardList[cardIndex]
    
    // 保存当前卡片信息到本地存储
    wx.setStorageSync('currentCardInfo', cardInfo)
    
    wx.navigateTo({
      url: `/pages/company/card-detail?cardId=${cardId}`
    })
  }
})